<?php

namespace app\common\model\cms;

use app\common\model\BaseModel;
use helper\Form;
use think\helper\Str;

class DetailModel extends BaseModel
{

  protected $table = 'cms_detail_';
  protected $suffix = 'article';

  /**
   * 解析模型表单
   * @param $tableName
   * @param array $data
   * @return array
   * @throws \Exception
   */
  public function getForm($tableName, $data = [])
  {
    $tableModel = new TableModel();
    $info       = $tableModel->getInfo($tableName);
    $form       = [];
    foreach ($info['fields'] as $v) {
      if ($v['obj_status'] == 0) continue;
      $_fun  = $v['obj_type'];
      $field = $v['field_name'];
      $value = $v['default_value'];
      if (isset($data[$v['field_name']])) $value = $data[$v['field_name']];
      $objOptions = $v['obj_options'];
      $screen     = !empty($data) ? 'edit' : 'add';
      //处理栏目默认选中
      if ($screen == 'add' && $field == 'class_id' && request()->has('class_id')) {
        $value = request()->param('class_id/d');
      }
      //处理前端验证
      if (isset($objOptions["datatype-{$screen}"])) {
        unset($objOptions["datatype-{$screen}"]);
        $objOptions['datatype'] = $objOptions["datatype-{$screen}"];
      }
      $form[$v['obj_location']][] = [
          'label_name' => $v['label_name'],
          'obj_tips' => $v['obj_tips'],
          'html' => Form::$_fun($field, $value, $objOptions)
      ];
    }
    return $form;
  }

  /**
   * 获取验证规则
   * @param $tableName
   * @param string $screen //验证场景
   * @return array
   * @throws \Exception
   */
  public function getValidRule($tableName, $screen = 'add')
  {
    $tableModel = new TableModel();
    $info       = $tableModel->getInfo($tableName);
    $validRule  = [];
    foreach ($info['fields'] as $v) {
      if ($v['obj_status'] == 0) continue;
      if (!empty($v['obj_valid'])) { //构建后端验证规则
        $valid = $v['obj_valid'];
        if (Str::contains($v['obj_valid'], '###')) {
          $validArr = explode('###', $v['obj_valid']);
          $valid    = $screen == 'add' ? $validArr[0] : $validArr[1];
        }
        $validRule["{$v['field_name']}|{$v['label_name']}"] = $valid;
      }
    }
    return $validRule;
  }

  /**
   * 添加内容
   * @param $data
   * @return bool
   * @throws \Exception
   */
  public function add($data)
  {
    $time = time();
    $data = $this->filterData($data);
    $data['create_time'] = $time;
    $data['update_time'] = $time;
    return DetailModel::suffix($data['table_name'])->strict(false)->insert($data);
  }

  /**
   * 编辑内容
   * @param $data
   * @return mixed
   * @throws \Exception
   */
  public function edit($data)
  {
    $time = time();
    $data                = $this->filterData($data);
    $data['update_time'] = $time;
    return self::suffix($data['table_name'])->strict(false)->update($data);
  }

  /**
   * 删除
   * @param $tableName
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($tableName, $id)
  {
    self::suffix($tableName)->where('id', 'in', $id)->delete();
    return true;
  }

  /**
   * 过滤数据
   * @param $data
   * @return mixed
   * @throws \Exception
   */
  private function filterData($data)
  {
    $fieldObjType = FieldModel::where('table_name', $data['table_name'])
        ->field('field_name,field_type,obj_type,obj_options')
        ->select()
        ->toArray();
    foreach ($fieldObjType as $v) {
      if ($v['obj_type'] == '_laydate' && isset($data[$v['field_name']])) {
        $value = $data[$v['field_name']];
        if ($v['field_type'] == 'int') {
          $data[$v['field_name']] = !empty($value) ? strtotime($value) : 0;
        }
        if (in_array($v['field_type'], ['date', 'datetime'])) {
          $data[$v['field_name']] = !empty($value) ? $value : null;
        }
      }
      if ($v['obj_type'] == '_switch') {
        $data[$v['field_name']] = isset($data[$v['field_name']]) ? 1 : 0;
      }
      if ($v['obj_type'] == '_checkbox') {
        $data[$v['field_name']] = isset($data[$v['field_name']]) ? implode(',', $data[$v['field_name']]) : '';
      }
      if ($v['obj_type'] == '_uploadImages') {
        if (isset($data[$v['field_name']])) {
          $objOptions = json_decode($v['obj_options'], true);
          $value      = $data[$v['field_name']];
          if ($objOptions['data-theme'] == 'multi01') {
            $data[$v['field_name']] = implode(',', array_column($value, 'file_url'));
          }
          if ($objOptions['data-theme'] == 'multi02') {
            $data[$v['field_name']] = json_encode(array_values($value), JSON_UNESCAPED_UNICODE);
          }
        } else {
          $data[$v['field_name']] = '';
        }
      }
      if ($v['obj_type'] == '_uploadFiles') {
        if (isset($data[$v['field_name']])) {
          $value      = $data[$v['field_name']];
          $data[$v['field_name']] = json_encode(array_values($value), JSON_UNESCAPED_UNICODE);
        } else {
          $data[$v['field_name']] = '';
        }
      }
    }
    return $data;
  }

}